package com.zhiyou100.service;

import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhiyou100.dao.DiscussDao;
import com.zhiyou100.dao.ProjectDao;

import com.zhiyou100.model.Discuss;
import com.zhiyou100.vo.PageVo;

@Service
public class DiscussServiceImpl implements DiscussService {

	@Autowired
	private ProjectDao projectDao;
	@Autowired
	private DiscussDao discussDao;

	@Override
	public PageVo<Discuss> getAllByProjectId(Integer projectId, Integer pageIndex, Integer pageSize) {
		// 获取数据总条数
		int dataCount = discussDao.discussCount(projectId);
		if (dataCount == 0) {
			// 如果总条数为0，没有数据，永远保持在第一页
			return new PageVo<Discuss>(1, pageSize, 0, 0, null);
		} else {
			int pageCount = (dataCount + pageSize - 1) / pageSize;
			if (pageIndex < 1) {
				pageIndex = 1;
			} else if (pageIndex > pageCount) {
				pageIndex = pageCount;
			}
			ArrayList<Discuss> discuss = discussDao.getAllByProjectId(projectId, (pageIndex - 1) * pageSize, pageSize);
			return new PageVo<>(pageIndex, pageSize, pageCount, dataCount, discuss);
		}
	}

	@Override
	public void addAllByProjectIdAndUserId(Discuss discuss) {
		discussDao.addAllByProjectIdAndUserId(discuss);
		projectDao.updateDiscuss(discuss.getProjectId());

	}

}
